﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using WorkRecord.CommonClass;

namespace WorkRecord
{
    public partial class WorkEnter : PageBase
    {
        public DataAccess da = new DataAccess();
        protected void Page_Load(object sender, EventArgs e)
        {
            //判断Session为null
            //to do
            if (!IsPostBack)
            {
                string user = WebContext.Current.CurrentUser.Rows[0]["username"].ToString();
                DataTable categoryDt;
                if (!da.CanEnter(user,out categoryDt))
                {
                    ShowAndRedirect(this.Page, "您没有录入权限，请联系管理员！", "/WorkView.aspx");
                }

                ddlTime_load();
                ddlWorkType_load();

                DataTable dt = CurrentDayJourney();
                if (dt.Rows.Count <= 0)
                    txtGuid.Text = System.Guid.NewGuid().ToString();
                else
                {
                    txtGuid.Text = dt.Rows[0]["Guid"].ToString();
                    BindArea();
                    BindContent();
                }
            }
        }

        private void AddArea(bool IsToday)
        {
            if (IsToday && (this.txtToDayArea.Text.Trim() == "" || this.txtToDayArea.Text == "所在城市"))
                return;
            if ((!IsToday) && (this.txtTomorrowArea.Text.Trim() == "" || this.txtTomorrowArea.Text == "所在城市"))
                return;
            string c = IsToday == true ? txtToDayArea.Text.Trim() : txtTomorrowArea.Text.Trim();
            if (check_city_exist(IsToday, c))
                return;

            SqlParameter[] paras = new SqlParameter[3];
            paras[0] = new SqlParameter("@Guid", txtGuid.Text);
            paras[1] = new SqlParameter("@Area", c);
            paras[2] = new SqlParameter("@IsToday", IsToday);
            string sql = @"insert into JourneyCities values(@Guid,@Area,@IsToday)";
            da.datacmd(sql, paras);
            BindArea();
        }
        private void DelArea(string ID)
        {
            string sql = string.Format("delete from JourneyCities where ID={0}", ID);
            da.datacmd(sql);
            BindArea();
        }
        private void BindArea()
        {
            string sql = string.Format(@"select * from JourneyCities where IsToday=1 and Guid='{0}'", txtGuid.Text);
            DataTable dt_today = da.readdata(sql);
            rptToDay.DataSource = dt_today;
            rptToDay.DataBind();
            if (dt_today.Rows.Count >= 3)
            {
                this.txtToDayArea.Visible = false;
                this.btnAddToDay.Visible = false;
            }
            else
            {
                this.txtToDayArea.Visible = true;
                this.btnAddToDay.Visible = true;
            }

            string tsql = string.Format(@"select * from JourneyCities where IsToday=0 and Guid='{0}'", txtGuid.Text);
            DataTable dt_tomorrow = da.readdata(tsql);
            rptTomorrow.DataSource = dt_tomorrow;
            rptTomorrow.DataBind();
            if (dt_tomorrow.Rows.Count >= 3)
            {
                this.txtTomorrowArea.Visible = false;
                this.btnAddTomorrow.Visible = false;
            }
            else
            {
                this.txtTomorrowArea.Visible = true;
                this.btnAddTomorrow.Visible = true;
            }
        }

        private void AddContents()
        {
            if (string.IsNullOrEmpty(this.txtContent.Text.Trim()))
                return;
            if (check_content_exist())
                return;

            SqlParameter[] paras = new SqlParameter[7];
            paras[0] = new SqlParameter("@Guid", txtGuid.Text);
            paras[1] = new SqlParameter("@StartHour", ddlStartH.SelectedValue);
            paras[2] = new SqlParameter("@StartMinute", "");
            paras[3] = new SqlParameter("EndHour", ddlEndH.SelectedValue);
            paras[4] = new SqlParameter("@EndMinute", "");
            paras[5] = new SqlParameter("@WorkType", ddlType.SelectedValue);
            paras[6] = new SqlParameter("@Contents", txtContent.Text);
            string sql = @"insert into JourneyContents values(@Guid,@StartHour,@StartMinute,@EndHour,@EndMinute,@WorkType,@Contents)";
            da.datacmd(sql, paras);
            BindContent();
            this.txtContent.Text = "";
            this.ddlType.SelectedIndex = 0;
            //check_ddlTime_add(this.ddlEndH.SelectedItem.Text);
            this.ddlStartH.SelectedValue = this.ddlEndH.SelectedValue;
        }
        private void DelContents(string id)
        {
            string sql = string.Format("delete from JourneyContents where ID={0}", id);
            da.datacmd(sql);
            BindContent();
            ddlTime_load();
        }
        private void BindContent()
        {
            string sql = string.Format("select * from JourneyContents where Guid='{0}'", txtGuid.Text);
            rptContent.DataSource = da.readdata(sql);
            rptContent.DataBind();
        }

        protected void btnAddToDay_Click(object sender, EventArgs e)
        {
            AddArea(true);
            txtToDayArea.Text = "";
        }

        protected void btnAddTomorrow_Click(object sender, EventArgs e)
        {
            AddArea(false);
            txtTomorrowArea.Text = "";
        }

        protected void rptToDay_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            if (e.CommandName == "del")
            {
                DelArea(e.CommandArgument.ToString());
            }
        }

        protected void rptTomorrow_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            if (e.CommandName == "del")
            {
                DelArea(e.CommandArgument.ToString());
            }
        }

        protected void btnContentAdd_Click(object sender, EventArgs e)
        {
            AddContents();
        }

        protected void rptContent_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            if (e.CommandName == "del")
            {
                DelContents(e.CommandArgument.ToString());
            }
        }

        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            if ((!check_citys_exist(true)) && (string.IsNullOrEmpty(this.txtToDayArea.Text.Trim()) || this.txtToDayArea.Text == "所在城市"))
                return;
            if ((!check_citys_exist(false)) && (string.IsNullOrEmpty(this.txtTomorrowArea.Text.Trim()) || this.txtTomorrowArea.Text == "所在城市"))
                return;
            if ((!check_contents_exist()) && string.IsNullOrEmpty(this.txtContent.Text.Trim()))
                return;

            if (!string.IsNullOrEmpty(txtToDayArea.Text.Trim()))
            {
                AddArea(true);
            }
            if (!string.IsNullOrEmpty(txtTomorrowArea.Text.Trim()))
            {
                AddArea(false);
            }
            if (!string.IsNullOrEmpty(txtContent.Text.Trim()))
            {
                AddContents();
            }
            SqlParameter[] paras = new SqlParameter[3];
            paras[0] = new SqlParameter("@Guid", txtGuid.Text);
            string user = WebContext.Current.CurrentUser.Rows[0]["username"].ToString();
            paras[1] = new SqlParameter("@UserAccount", user);
            paras[2] = new SqlParameter("@SubmitTime", DateTime.Now);
            if (CurrentDayJourney().Rows.Count <= 0)
            {
                string sql = "insert into Journeys values(@Guid,@UserAccount,@SubmitTime)";
                da.datacmd(sql, paras);
            }
            else
            {
                //da.datacmd("update")
            }
            Response.Redirect("WorkView.aspx");
        }

        private DataTable CurrentDayJourney()
        {
            string user = WebContext.Current.CurrentUser.Rows[0]["username"].ToString();
            string exitsSql = string.Format(@"select * from Journeys where UserAccount='{0}' and CONVERT(varchar(100), SubmitTime, 23)='{1}'", user, DateTime.Now.ToString("yyyy-MM-dd"));
            return da.readdata(exitsSql);
        }

        protected void bnReset_Click(object sender, EventArgs e)
        {
            //txtToDayArea.Text = "";
            //txtTomorrowArea.Text = "";
            //txtContent.Text = "";
        }

        private bool check_content_exist()
        {
            DataTable dt = da.readdata("select * from JourneyContents where guid='" + this.txtGuid.Text.Replace("'", "") + "' and StartHour='" + this.ddlStartH.SelectedValue + "' and EndHour='" + this.ddlEndH.SelectedValue + "'");
            if (dt.Rows.Count > 0)
                return true;
            else
                return false;
        }
        private bool check_city_exist(bool istoday, string city)
        {
            DataTable dt = da.readdata("select * from JourneyCities where guid='" + this.txtGuid.Text.Replace("'", "") + "' and IsToday='" + istoday + "' and Area='" + city.Replace("'", "") + "'");
            if (dt.Rows.Count > 0)
                return true;
            else
                return false;
        }
        private bool check_citys_exist(bool istoday)
        {
            DataTable dt = da.readdata("select * from JourneyCities where guid='" + this.txtGuid.Text.Replace("'", "") + "' and IsToday='" + istoday + "'");
            if (dt.Rows.Count > 0)
                return true;
            else
                return false;
        }
        private bool check_contents_exist()
        {
            DataTable dt = da.readdata("select * from JourneyContents where guid='" + this.txtGuid.Text.Replace("'", "") + "'");
            if (dt.Rows.Count > 0)
                return true;
            else
                return false;
        }

        private void ddlTime_load()
        {
            this.ddlStartH.Items.Clear();
            this.ddlEndH.Items.Clear();
            for (int i = 0; i < 24; i++)
            {
                this.ddlStartH.Items.Add(i.ToString() + ":00");
                this.ddlStartH.Items.Add(i.ToString() + ":30");
                this.ddlEndH.Items.Add(i.ToString() + ":00");
                this.ddlEndH.Items.Add(i.ToString() + ":30");
            }
            this.ddlStartH.Items.Add("24:00");
            this.ddlEndH.Items.Add("24:00");
            this.ddlStartH.SelectedValue = "9:00";
            this.ddlEndH.SelectedValue = "9:00";
        }
        protected void ddlStartH_SelectedIndexChanged(object sender, EventArgs e)
        {
            /*this.ddlEndH.Items.Clear();
            int startH_select_index = this.ddlStartH.SelectedIndex;
            for (int i = startH_select_index; i < this.ddlStartH.Items.Count; i++)
                this.ddlEndH.Items.Add(this.ddlStartH.Items[i]);
            this.ddlEndH.Enabled = true;*/
        }
        /*private void check_ddlTime_add(string t)
        {
            List<string> temp_lis = new List<string>();
            bool flag = false;
            foreach (ListItem li in this.ddlStartH.Items)
            {
                if (li.Text == t)
                    flag = true;
                if (flag)
                    temp_lis.Add(li.Text);
            }
            this.ddlStartH.Items.Clear();
            this.ddlEndH.Items.Clear();
            foreach (string s in temp_lis)
            {
                ListItem li = new ListItem(s);
                this.ddlStartH.Items.Add(li);
                this.ddlEndH.Items.Add(li);
            }
        }*/

        private void ddlWorkType_load()
        {
            this.ddlType.Items.Clear();
            System.Xml.XmlDocument xd = new System.Xml.XmlDocument();
            xd.Load(Server.MapPath("WorkType.xml"));
            System.Xml.XmlNodeList xnl = xd.SelectNodes("/WorkType/listitem");
            for (int i = 0; i < xnl.Count; i++)
            {
                ListItem li = new ListItem(xnl.Item(i).Attributes["text"].Value);
                this.ddlType.Items.Add(li);
            }
        }
    }
}